﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.PlcWriteDbDomain;
using Zocono.WCS.Domain.RouteDomain;

namespace Zocono.WCS.HangfireHost.TaskJobs
{
    /// <summary>
    /// 一次作业读取存到缓存
    /// </summary>
    public class OnceJobQz
    {
        private readonly IRouteInfoService _routeInfoService;
        private readonly IRouteDetailInfoService _routeDetailInfoService;
        private readonly IPlcWriteDbInfoService _plcWriteDbInfoService;
        private readonly ILogUtil _logUtil;
        private readonly TaskLock _taskLock;

        public OnceJobQz(
            IRouteInfoService routeInfoService,
            IRouteDetailInfoService routeDetailInfoService,
            IPlcWriteDbInfoService plcWriteDbInfoService,
            ILogUtil logUtil,
            TaskLock taskLock)
        {
            _routeInfoService = routeInfoService;
            _routeDetailInfoService = routeDetailInfoService;
            _plcWriteDbInfoService = plcWriteDbInfoService;
            _logUtil = logUtil;
            _taskLock = taskLock;
        }

        /// <summary>
        /// 执行作业任务
        /// </summary>
        /// <returns></returns>
        public async Task DoJob()
        {
            if (_taskLock.OnceTaskLock)
            {
                return;
            }
            try
            {
                _taskLock.OnceTaskLock = true;
                await _routeInfoService.GetRouteInfoListFromRedisAsync();
                await _routeDetailInfoService.GetRouteDetailInfoListAsync();
                await _plcWriteDbInfoService.GetPlcWriteDbInfoListAsync();
            }
            catch (Exception ex)
            {
                _logUtil.Error($"获取配到内存作业报错ex={ex}");
            }
            finally
            {
                _taskLock.OnceTaskLock = false;
                _logUtil.Debug($"获取配到内存作业完成");
            }
        }

        /// <summary>
        /// 使用hangfire时调用
        /// </summary>
        /// <returns></returns>
        public async Task HangfireJob()
        {
            await DoJob();
        }
    }
}
